package com.gnerv.battle.boot.framework.core.advice.api;

import com.gnerv.battle.boot.framework.core.annotation.api.ApiResponseEncrypt;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.io.Serializable;

/**
 * 加密响应类
 *
 * @author hermes-di
 * @since 1.0.0.RELEASE
 **/
@Slf4j
@RestControllerAdvice
public class ApiEncryptResponseBodyAdvice implements ResponseBodyAdvice<Object>, Serializable {

    @Resource
    private ApiCryptoService apiCryptoService;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> clazz) {
        return methodParameter.hasMethodAnnotation(ApiResponseEncrypt.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> clazz, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return apiCryptoService.encrypt(body, methodParameter, mediaType, clazz, serverHttpRequest, serverHttpResponse);
    }
}